package org.jhotdraw.samples.phototemplate;

import com.jhlabs.image.ContrastFilter;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import org.imgscalr.Scalr;
import org.jhotdraw.draw.AbstractFigure;
import org.jhotdraw.draw.AttributeKey;
import org.jhotdraw.draw.AttributeKeys;
import org.jhotdraw.draw.DefaultDrawingEditor;
import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.DrawingEditor;
import org.jhotdraw.draw.DrawingView;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.QuadTreeDrawing;
import org.jhotdraw.draw.event.FigureEvent;
import org.jhotdraw.draw.event.FigureListener;
import org.jhotdraw.draw.io.ImageInputFormat;
import org.jhotdraw.draw.io.ImageOutputFormat;
import org.jhotdraw.draw.io.InputFormat;
import org.jhotdraw.draw.io.OutputFormat;
import org.jhotdraw.draw.io.SerializationInputOutputFormat;
import org.jhotdraw.draw.io.TextInputFormat;
import org.jhotdraw.draw.tool.SelectionTool;
import org.jhotdraw.draw.tool.Tool;
import org.jhotdraw.samples.svg.SVGAttributeKeys;
import org.jhotdraw.samples.svg.figures.SVGImageFigure;
import org.jhotdraw.samples.svg.figures.SVGRectFigure;
import org.jhotdraw.samples.svg.figures.SVGTextFigure;
import org.jhotdraw.samples.svg.io.ImageMapOutputFormat;
import org.jhotdraw.samples.svg.io.SVGInputFormat;
import org.jhotdraw.samples.svg.io.SVGOutputFormat;
import org.jhotdraw.samples.svg.io.SVGZInputFormat;
import org.jhotdraw.samples.svg.io.SVGZOutputFormat;

/**
 *
 * @author Eliazar
 */
public class EditionImageDialog extends javax.swing.JDialog {

    private URI uriImage;
    double[] factorsZoom = {0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2};
    int currentZoom = 0;
    private SVGRectFigure rectanguleSelection;
    private SelectionTool selectionTool;
    private BufferedImage newBufferedImage;
    private DrawingEditor editor;
    private ContrastFilter contrastFilter;
    private BufferedImage destinationBufferedImage, sourceBufferedImage;
    private enum operation {FLIP, NEGATIVE, BRIGTHNESS_P, BRIGTHNESS_M, CONTRAST_P, CONTRAST_M};
    private URI editedFigure;
    
    
    public EditionImageDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        view.setDrawing(createDrawing());
        editor = new DefaultDrawingEditor();
        editor.add(view);
        btCut.setVisible(false);
        selectionTool = new SelectionTool();
        editor.setTool(selectionTool);
        contrastFilter = new ContrastFilter();
        contrastFilter.setBrightness(1F);
        contrastFilter.setContrast(1F);
    }

    public EditionImageDialog(java.awt.Frame parent, boolean modal, URI uriImage) {
        this(parent, modal);
        this.uriImage = uriImage;
        loadImage();
        updateScaleFactor();
    }

    public BufferedImage getNewBufferedImage() {
        return newBufferedImage;
    }

    public URI getEditedFigure() {
        return editedFigure;
    }

    public void setEditedFigure(URI selectedFigure) {
        this.editedFigure = selectedFigure;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        view = new org.jhotdraw.draw.DefaultDrawingView();
        jToolBar1 = new javax.swing.JToolBar();
        btTurnLeft = new javax.swing.JButton();
        btTurnRight = new javax.swing.JButton();
        btFlip = new javax.swing.JButton();
        btNegative = new javax.swing.JButton();
        btSelection = new javax.swing.JToggleButton();
        btCut = new javax.swing.JButton();
        btZoomIn = new javax.swing.JButton();
        btZoomOut = new javax.swing.JButton();
        btZoomFit = new javax.swing.JButton();
        btBrightnessPLus = new javax.swing.JButton();
        btBrightnessMenus = new javax.swing.JButton();
        ConstrastPLus = new javax.swing.JButton();
        ConstrastMenus = new javax.swing.JButton();
        btSave = new javax.swing.JButton();
        btApply = new javax.swing.JButton();
        labelZoom = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jPanel2 = new javax.swing.JPanel();
        lbBrightness = new javax.swing.JLabel();
        lbContrast = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Editar Imagem");
        setModal(true);
        setPreferredSize(new java.awt.Dimension(800, 600));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                releaseResources(evt);
            }
        });

        jPanel1.setPreferredSize(new java.awt.Dimension(8, 8));

        view.setPreferredSize(new java.awt.Dimension(800, 600));
        jScrollPane1.setViewportView(view);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 729, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        btTurnLeft.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/arrow-left-32.png"))); // NOI18N
        btTurnLeft.setToolTipText("Rotação para a esquerda");
        btTurnLeft.setFocusable(false);
        btTurnLeft.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btTurnLeft.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btTurnLeft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btTurnRightbtTurnLeftOrRightActionPerformed(evt);
            }
        });
        jToolBar1.add(btTurnLeft);

        btTurnRight.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/arrow-right-32.png"))); // NOI18N
        btTurnRight.setToolTipText("Rotação para a direita");
        btTurnRight.setFocusable(false);
        btTurnRight.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btTurnRight.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btTurnRight.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btTurnRightbtTurnLeftOrRightActionPerformed(evt);
            }
        });
        jToolBar1.add(btTurnRight);

        btFlip.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/flip.png"))); // NOI18N
        btFlip.setToolTipText("Espelhar");
        btFlip.setFocusable(false);
        btFlip.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btFlip.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btFlip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFlipActionPerformed(evt);
            }
        });
        jToolBar1.add(btFlip);

        btNegative.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/black-white-icon.png"))); // NOI18N
        btNegative.setToolTipText("Negativo");
        btNegative.setFocusable(false);
        btNegative.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btNegative.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btNegative.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNegativeActionPerformed(evt);
            }
        });
        jToolBar1.add(btNegative);

        btSelection.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/selection.png"))); // NOI18N
        btSelection.setToolTipText("Seleção retangular");
        btSelection.setFocusable(false);
        btSelection.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btSelection.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btSelection.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                btSelectionItemStateChanged(evt);
            }
        });
        btSelection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSelectionActionPerformed(evt);
            }
        });
        jToolBar1.add(btSelection);

        btCut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/Editing-Cut-icon.png"))); // NOI18N
        btCut.setToolTipText("Recortar seleção");
        btCut.setFocusable(false);
        btCut.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btCut.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btCut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCutActionPerformed(evt);
            }
        });
        jToolBar1.add(btCut);

        btZoomIn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/Zoom-In-32px.png"))); // NOI18N
        btZoomIn.setToolTipText("Ampliar");
        btZoomIn.setFocusable(false);
        btZoomIn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btZoomIn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btZoomIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btZoomInActionPerformed(evt);
            }
        });
        jToolBar1.add(btZoomIn);

        btZoomOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/Zoom-Out-32.png"))); // NOI18N
        btZoomOut.setToolTipText("Diminuir");
        btZoomOut.setFocusable(false);
        btZoomOut.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btZoomOut.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btZoomOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btZoomOutActionPerformed(evt);
            }
        });
        jToolBar1.add(btZoomOut);

        btZoomFit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/Zoom-original-32px.png"))); // NOI18N
        btZoomFit.setToolTipText("Tamanho original");
        btZoomFit.setFocusable(false);
        btZoomFit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btZoomFit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btZoomFit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btZoomFitActionPerformed(evt);
            }
        });
        jToolBar1.add(btZoomFit);

        btBrightnessPLus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/brightness_brighten_32.png"))); // NOI18N
        btBrightnessPLus.setToolTipText("Aumentar brilho");
        btBrightnessPLus.setFocusable(false);
        btBrightnessPLus.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btBrightnessPLus.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btBrightnessPLus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBrightnessPLusActionPerformed(evt);
            }
        });
        jToolBar1.add(btBrightnessPLus);

        btBrightnessMenus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/brightness_darken_32.png"))); // NOI18N
        btBrightnessMenus.setToolTipText("Reduzir brilho");
        btBrightnessMenus.setFocusable(false);
        btBrightnessMenus.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btBrightnessMenus.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btBrightnessMenus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBrightnessMenusActionPerformed(evt);
            }
        });
        jToolBar1.add(btBrightnessMenus);

        ConstrastPLus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/contrast-increase-icon.png"))); // NOI18N
        ConstrastPLus.setToolTipText("Aumentar contraste");
        ConstrastPLus.setFocusable(false);
        ConstrastPLus.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ConstrastPLus.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        ConstrastPLus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConstrastPLusActionPerformed(evt);
            }
        });
        jToolBar1.add(ConstrastPLus);

        ConstrastMenus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/contrast-decrease-icon.png"))); // NOI18N
        ConstrastMenus.setToolTipText("Reduzir contraste");
        ConstrastMenus.setFocusable(false);
        ConstrastMenus.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        ConstrastMenus.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        ConstrastMenus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConstrastMenusActionPerformed(evt);
            }
        });
        jToolBar1.add(ConstrastMenus);

        btSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/save.png"))); // NOI18N
        btSave.setToolTipText("Salvar alterações em arquivo");
        btSave.setFocusable(false);
        btSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSaveActionPerformed(evt);
            }
        });
        jToolBar1.add(btSave);

        btApply.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jhotdraw/samples/phototemplate/images/apply-template.png"))); // NOI18N
        btApply.setToolTipText("Aplicar ao template");
        btApply.setFocusable(false);
        btApply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btApply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btApplyActionPerformed(evt);
            }
        });
        jToolBar1.add(btApply);
        jToolBar1.add(labelZoom);
        jToolBar1.add(jSeparator1);

        jPanel2.setLayout(new java.awt.GridLayout(2, 0));

        lbBrightness.setToolTipText("");
        jPanel2.add(lbBrightness);

        lbContrast.setToolTipText("");
        jPanel2.add(lbContrast);

        jToolBar1.add(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 729, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 729, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 305, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(50, 50, 50)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btTurnRightbtTurnLeftOrRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTurnRightbtTurnLeftOrRightActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        BufferedImage bi;
        SVGImageFigure figure = getImageFigureFromView();
        view.setDrawing(createDrawing());
        if (evt.getSource() == btTurnLeft) {
            bi = Scalr.rotate(figure.getBufferedImage(), Scalr.Rotation.CW_270);
            sourceBufferedImage = Scalr.rotate(sourceBufferedImage, Scalr.Rotation.CW_270);
        } else {
            bi = Scalr.rotate(figure.getBufferedImage(), Scalr.Rotation.CW_90);
            sourceBufferedImage = Scalr.rotate(sourceBufferedImage, Scalr.Rotation.CW_90);
        }
        figure = new SVGImageFigure(0, 0, bi.getWidth(), bi.getHeight());
        figure.setBufferedImage(bi);
        view.getDrawing().add(figure);
        figure.setSelectable(false);
        btSelection.setSelected(false);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        destinationBufferedImage = null;
        System.gc();
    }//GEN-LAST:event_btTurnRightbtTurnLeftOrRightActionPerformed

    private void btFlipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFlipActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        SVGImageFigure figure = getImageFigureFromView();
        figure.setBufferedImage(ImageUtils.getImageFlip(figure.getBufferedImage()));
        sourceBufferedImage = ImageUtils.getImageFlip(sourceBufferedImage);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));        
        destinationBufferedImage = null;
        System.gc();
    }//GEN-LAST:event_btFlipActionPerformed

    private void btNegativeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNegativeActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        SVGImageFigure figure = getImageFigureFromView();
        figure.setBufferedImage((BufferedImage) ImageUtils.getNegativeImage(figure.getBufferedImage()));
        sourceBufferedImage = (BufferedImage) ImageUtils.getNegativeImage(sourceBufferedImage);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));        
        destinationBufferedImage = null;
        System.gc();
    }//GEN-LAST:event_btNegativeActionPerformed

    private void btSelectionItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_btSelectionItemStateChanged
        if (rectanguleSelection == null) {
            Map<AttributeKey, Object> attributes = new HashMap<AttributeKey, Object>();
            attributes.put(AttributeKeys.STROKE_COLOR, Color.CYAN);
            attributes.put(AttributeKeys.STROKE_WIDTH, 5D);
            attributes.put(SVGAttributeKeys.FILL_OPACITY, 0D);
            rectanguleSelection = new SVGRectFigure(0, 0, 300D, 200D);
            rectanguleSelection.setAttributes(attributes);
            rectanguleSelection.addFigureListener(new FigureListenerAdapter());
        }
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            view.getDrawing().add(rectanguleSelection);
            view.getDrawing().bringToFront(rectanguleSelection);
        } else {
            view.getDrawing().remove(rectanguleSelection);
            rectanguleSelection = null;
        }
        btCut.setVisible(evt.getStateChange() == ItemEvent.SELECTED);
        
    }//GEN-LAST:event_btSelectionItemStateChanged

    private void btCutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCutActionPerformed

        Point2D.Double startPoint = rectanguleSelection.getStartPoint();
        Point2D.Double endPoint = rectanguleSelection.getEndPoint();
        SVGImageFigure figure = getImageFigureFromView();
        if (figure != null && figure.contains(startPoint) && figure.contains(endPoint)) {
            int x, y, w, h;
            x = Double.valueOf(rectanguleSelection.getX()).intValue();
            y = Double.valueOf(rectanguleSelection.getY()).intValue();
            w = Double.valueOf(rectanguleSelection.getWidth()).intValue();
            h = Double.valueOf(rectanguleSelection.getHeight()).intValue();
            BufferedImage bf = Scalr.crop(figure.getBufferedImage(), x, y, w, h);
            sourceBufferedImage = Scalr.crop(sourceBufferedImage, x, y, w, h);
            view.getDrawing().remove(figure);
            figure = new SVGImageFigure(0, 0, w, h);
            figure.setBufferedImage(bf);
            view.getDrawing().add(figure);
            figure.setSelectable(false);
            view.getDrawing().remove(rectanguleSelection);
            rectanguleSelection = null;
            btSelection.setSelected(false);
        }
        destinationBufferedImage = null;
        System.gc();
    }//GEN-LAST:event_btCutActionPerformed

    private void btZoomInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btZoomInActionPerformed
        if (currentZoom < factorsZoom.length - 1) {
            currentZoom++;
            updateScaleFactor();
        }
    }//GEN-LAST:event_btZoomInActionPerformed

    private void btZoomOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btZoomOutActionPerformed
        if (currentZoom >= 1) {
            currentZoom--;
            updateScaleFactor();
        }
    }//GEN-LAST:event_btZoomOutActionPerformed

    private void btZoomFitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btZoomFitActionPerformed
        currentZoom = 3;
        updateScaleFactor();
    }//GEN-LAST:event_btZoomFitActionPerformed

    private void btSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveActionPerformed
        String dir = Utilities.getProperty(Utilities.KEY.DIR_FOTOS);
        JFileChooser chooser = new JFileChooser(dir);
        if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {                                                                    
                setCursor(new Cursor(Cursor.WAIT_CURSOR));
                String extension = Utilities.getExtension(chooser.getSelectedFile());            
                BufferedImage image=null;
                image = contrastFilter.filter(sourceBufferedImage, image);            
                if (extension != null && extension.equalsIgnoreCase("png")) {
                        ImageIO.write(image, "png", chooser.getSelectedFile());
                        MessageDialog.showMessageOk(this);                    
                } else if (extension != null && extension.equalsIgnoreCase("jpg")) {                    
                        ImageIO.write(image, "jpg", chooser.getSelectedFile());
                        MessageDialog.showMessageOk(this);             
                } else {
                    MessageDialog.showMessageFail(this, "Informe o nome de um arquivo com a extensão .png ou .jpg");
                }
            } catch (IOException ex) {
                MessageDialog.showMessageFail(this, "Falha ao salvar a imagem no arquivo");
            } finally {
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            }    
        }
    }//GEN-LAST:event_btSaveActionPerformed

    private void btApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btApplyActionPerformed
        try {
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            Random random = new Random();
            String fileName = random.nextInt(Integer.MAX_VALUE) + ".png";
            File file = new File(Utilities.directoryTemp + "/" + fileName);
            newBufferedImage = contrastFilter.filter(sourceBufferedImage, newBufferedImage);        
            ImageIO.write(newBufferedImage, "png", file);
            editedFigure = file.toURI(); 
            setVisible(false);
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        } catch (IOException ex) {
            Logger.getLogger(EditionImageDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btApplyActionPerformed

    private void releaseResources(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_releaseResources
        editor = null;
        view.setDrawing(null);
        view = null;
        System.gc();
    }//GEN-LAST:event_releaseResources
    
    private void btBrightnessPLusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBrightnessPLusActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        if(contrastFilter.getBrightness() < 2) {
            contrastFilter.setBrightness(Double.valueOf(contrastFilter.getBrightness() + 0.1).floatValue());
            SVGImageFigure figure = getImageFigureFromView();      
            destinationBufferedImage = contrastFilter.filter(sourceBufferedImage, destinationBufferedImage);                        
            figure.setBufferedImage(destinationBufferedImage);                       
        }
        String text = "Brilho " + Double.valueOf(contrastFilter.getBrightness() * 100).intValue() + "%";                
        lbBrightness.setText(text);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        System.gc();
    }//GEN-LAST:event_btBrightnessPLusActionPerformed
       
    private void btBrightnessMenusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBrightnessMenusActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        if(contrastFilter.getBrightness() >= 0.1) {
            contrastFilter.setBrightness(Double.valueOf(contrastFilter.getBrightness() - 0.1).floatValue());
            SVGImageFigure figure = getImageFigureFromView(); 
            destinationBufferedImage = contrastFilter.filter(sourceBufferedImage, destinationBufferedImage);                        
            figure.setBufferedImage(destinationBufferedImage);
        }
        String text = "Brilho " + Double.valueOf(contrastFilter.getBrightness() * 100).intValue()+ "%";        
        lbBrightness.setText(text);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        System.gc();
    }//GEN-LAST:event_btBrightnessMenusActionPerformed

    private void ConstrastPLusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConstrastPLusActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        if(contrastFilter.getContrast() < 2) {
            contrastFilter.setContrast(Double.valueOf(contrastFilter.getContrast() + 0.1).floatValue());
            SVGImageFigure figure = getImageFigureFromView();
            destinationBufferedImage = contrastFilter.filter(sourceBufferedImage, destinationBufferedImage);                        
            figure.setBufferedImage(destinationBufferedImage);
        }
        String text = "Contraste " + Double.valueOf(contrastFilter.getContrast() * 100).intValue()+ "%";
        lbContrast.setText(text);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        System.gc();
    }//GEN-LAST:event_ConstrastPLusActionPerformed

    private void ConstrastMenusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConstrastMenusActionPerformed
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        if(contrastFilter.getContrast() >= 0.1) {
            contrastFilter.setContrast(Double.valueOf(contrastFilter.getContrast() - 0.1).floatValue());
            SVGImageFigure figure = getImageFigureFromView();
            destinationBufferedImage = contrastFilter.filter(sourceBufferedImage, destinationBufferedImage);                        
            figure.setBufferedImage(destinationBufferedImage);
        }
        String text = "Contraste " + Double.valueOf(contrastFilter.getContrast() * 100).intValue()+ "%";
        lbContrast.setText(text);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        System.gc();
    }//GEN-LAST:event_ConstrastMenusActionPerformed

    private void btSelectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSelectionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btSelectionActionPerformed
       
    private Drawing createDrawing() {
        Drawing drawing = new QuadTreeDrawing();
        LinkedList<InputFormat> inputFormats = getInputFormats();
        drawing.setInputFormats(inputFormats);

        LinkedList<OutputFormat> outputFormats = new LinkedList<OutputFormat>();
        outputFormats.add(new SVGOutputFormat());
        outputFormats.add(new SVGZOutputFormat());
        outputFormats.add(new ImageOutputFormat());
        outputFormats.add(new ImageOutputFormat("JPG", "Joint Photographics Experts Group (JPEG)", "jpg", BufferedImage.TYPE_INT_RGB));
        outputFormats.add(new ImageOutputFormat("BMP", "Windows Bitmap (BMP)", "bmp", BufferedImage.TYPE_BYTE_INDEXED));
        outputFormats.add(new ImageMapOutputFormat());
        outputFormats.add(new SerializationInputOutputFormat());
        drawing.setOutputFormats(outputFormats);

        return drawing;
    }

    private LinkedList<InputFormat> getInputFormats() {
        LinkedList<InputFormat> inputFormats = new LinkedList<InputFormat>();
        inputFormats.add(new SVGZInputFormat());
        inputFormats.add(new SVGInputFormat());
        inputFormats.add(new ImageInputFormat(new SVGImageFigure(), "PNG", "Portable Network Graphics (PNG)", "png", "image/png"));
        inputFormats.add(new ImageInputFormat(new SVGImageFigure(), "JPG", "Joint Photographics Experts Group (JPEG)", "jpg", "image/jpg"));
        inputFormats.add(new ImageInputFormat(new SVGImageFigure(), "GIF", "Graphics Interchange Format (GIF)", "gif", "image/gif"));
        inputFormats.add(new TextInputFormat(new SVGTextFigure()));
        inputFormats.add(new SerializationInputOutputFormat());
        return inputFormats;
    }   

    private void loadImage() {
        LinkedList<InputFormat> inputFormats = getInputFormats();
        for (InputFormat format : inputFormats) {
            try {
                format.read(uriImage, view.getDrawing(), true);
                AbstractFigure figure = (AbstractFigure) view.getDrawing().getChild(0);
                sourceBufferedImage = ((SVGImageFigure)figure).getBufferedImage();
                figure.setSelectable(false);
                view.setDrawing(createDrawing());
                view.getDrawing().add(figure);
                return;
            } catch (IOException ex) {
            }
        }
        MessageDialog.showMessageFail(this, "A imagem possui um formato não suportado.");
    }

    private void updateScaleFactor() {
        view.setScaleFactor(factorsZoom[currentZoom]);
        labelZoom.setText("      Zoom " + factorsZoom[currentZoom] * 100 + "%");
    }

    private SVGImageFigure getImageFigureFromView() {
        for (Figure figure : view.getDrawing().getChildren()) {
            if (figure instanceof SVGImageFigure) {
                return (SVGImageFigure) figure;
            }
        }
        return null;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ConstrastMenus;
    private javax.swing.JButton ConstrastPLus;
    private javax.swing.JButton btApply;
    private javax.swing.JButton btBrightnessMenus;
    private javax.swing.JButton btBrightnessPLus;
    private javax.swing.JButton btCut;
    private javax.swing.JButton btFlip;
    private javax.swing.JButton btNegative;
    private javax.swing.JButton btSave;
    private javax.swing.JToggleButton btSelection;
    private javax.swing.JButton btTurnLeft;
    private javax.swing.JButton btTurnRight;
    private javax.swing.JButton btZoomFit;
    private javax.swing.JButton btZoomIn;
    private javax.swing.JButton btZoomOut;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel labelZoom;
    private javax.swing.JLabel lbBrightness;
    private javax.swing.JLabel lbContrast;
    private org.jhotdraw.draw.DefaultDrawingView view;
    // End of variables declaration//GEN-END:variables

    private class FigureListenerAdapter implements FigureListener {

        @Override
        public void areaInvalidated(FigureEvent e) {
        }

        @Override
        public void attributeChanged(FigureEvent e) {
        }

        @Override
        public void figureHandlesChanged(FigureEvent e) {
        }

        @Override
        public void figureChanged(FigureEvent e) {
        }

        @Override
        public void figureAdded(FigureEvent e) {
        }

        @Override
        public void figureRemoved(FigureEvent e) {
            rectanguleSelection = null;
            btCut.setVisible(false);
            btSelection.setSelected(false);
        }

        @Override
        public void figureRequestRemove(FigureEvent e) {
        }
    }
    
     /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RectangulePropertiesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RectangulePropertiesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RectangulePropertiesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RectangulePropertiesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                EditionImageDialog dialog = new EditionImageDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
}
